package com.zy.qudadid.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pingplusplus.android.Pingpp;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zy.base.BaseActivity;
import com.zy.bean.Dingdan;
import com.zy.lcpassenger.R;
import com.zy.qudadid.model.Stroke;
import com.zy.qudadid.model.StrokeInfor;
import com.zy.qudadid.network.Const;
import com.zy.qudadid.presenter.base.BasePresenterImp;
import com.zy.qudadid.ui.activity.base.ToolBarActivity;
import com.zy.qudadid.utils.AESCrypt;
import com.zy.qudadid.utils.StringUtil;
import com.zy.util.JsonUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import okhttp3.Call;

/**
 * Created by Administrator on 2016/7/21 0021.
 */
public class ZhifuActivity extends ToolBarActivity {

//    ImageView back;
    StrokeInfor dingdan;
    Button z_zhifu;
    TextView z_money;
//    RelativeLayout z_youhuiquan;
    CheckBox z_weixin,z_xianjin,z_zhifubao;
    RelativeLayout rlCash;
    private int num = -1;
    private String cid = "0";
    TextView z_xiaofei;
    LinearLayout ll_tip;

    private String price="";

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_zhifuyemian;
    }

    @Override
    public void initListeners() {

    }

    @Override
    protected void initThings(Bundle savedInstanceState) {
        super.initThings(savedInstanceState);

        dingdan = (StrokeInfor) getIntent().getBundleExtra("data").getSerializable("dingdan");

//        back = (ImageView) findViewById(R.id.back);
        rlCash = (RelativeLayout) findViewById(R.id.rlCash);
        if(dingdan.state.equals("8")){ //
            rlCash.setVisibility(View.GONE);
        }else{
            rlCash.setVisibility(View.VISIBLE);
        }

//        Map map = new HashMap();
//        map.put("order_id", dingdan.oid);
//        map.put("type",1+"");
//        map.put("user_id",new UserUtil(getBaseContext()).getUserId());
//        String json = StringUtil.toJson(map);
//        try {
//            String data = com.xfyc.qudadid.utils.AESCrypt.getInstance().encrypt(json);
//            String d = StringUtil.replaceBlank(data);
//
//            OkHttpUtils.post()
//                    .url(Const.BASE_URL+"api.php/Order/order_details")
//                    .addParams("args","d")
//                    .build()
//                    .execute(new StringCallback() {
//                        @Override
//                        public void onError(Call call,Exception e, int i) {
//
//                        }
//
//                        @Override
//                        public void onResponse(String response, int i) {
//                            JSONObject json;
//                            try {
//                                json = new JSONObject(response);
//                                int code = json.getInt("code");
//                                if(code == 200){
//                                    dingdan = new Gson().fromJson(json.getJSONObject("datas").toString(),Dingdan.class);
//                                    if(Double.parseDouble(dingdan.tip)>0) {
//                                        ll_tip.setVisibility(View.VISIBLE);
//                                        z_xiaofei.setText(dingdan.tip);
//                                    }else{
//                                        ll_tip.setVisibility(View.GONE);
//                                    }
//                                }
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//
//                        }
//                    });
//        } catch (Exception ex) {
//        }

        z_money = (TextView)findViewById(R.id.z_money);
        z_xiaofei = (TextView)findViewById(R.id.z_xiaofei);
//        youhuiquan = (TextView)findViewById(R.id.youhuiquan);
        z_weixin = (CheckBox)findViewById(R.id.z_weixin);
//        z_youhuiquan = (RelativeLayout)findViewById(R.id.z_youhuiquan);
        z_xianjin = (CheckBox)findViewById(R.id.z_xianjin);
//        z_yue = (CheckBox)findViewById(R.id.z_yue);
        z_zhifubao = (CheckBox)findViewById(R.id.z_zhifubao);
        z_zhifu = (Button)findViewById(R.id.z_zhifu);
        ll_tip = (LinearLayout) findViewById(R.id.ll_tip);
        z_money.setText(dingdan.price);

        price = dingdan.price;

        if(Double.parseDouble(dingdan.tip)>0) {
            ll_tip.setVisibility(View.VISIBLE);
            z_xiaofei.setText(dingdan.tip);

            price = (Double.parseDouble(dingdan.price)+Double.parseDouble(dingdan.tip))+"";
        }else{
            ll_tip.setVisibility(View.GONE);
        }

//        back.setOnClickListener(this);

//        z_youhuiquan.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivityForResult(YilingyouhuijuanNewActivity.class, 1021);
//            }
//        });

        z_weixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = 0;
                channel = "wx";
                z_xianjin.setChecked(false);
//                z_yue.setChecked(false);
                z_zhifubao.setChecked(false);
            }
        });

        z_xianjin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = 1;
                z_weixin.setChecked(false);
//                z_yue.setChecked(false);
                z_zhifubao.setChecked(false);
            }
        });

//        z_yue.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                num = 2;
//                z_xianjin.setChecked(false);
//                z_weixin.setChecked(false);
//                z_zhifubao.setChecked(false);
//            }
//        });

        z_zhifubao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num = 3;
                channel = "alipay";
                z_xianjin.setChecked(false);
//                z_yue.setChecked(false);
                z_weixin.setChecked(false);
            }
        });

        z_zhifu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (num){
                    case 0:
                        pay();
                        break;
                    case 1:
                        offPay();
                        break;
//                    case 2:
//                        yuePay();
//                        break;
                    case 3:
                        pay();
                        break;
                }
            }
        });
    }

    @Override
    public BasePresenterImp createPresenter() {
        return null;
    }


    public void startActivityForResult(Class clazz, int requestCode) {
        startActivityForResult(new Intent(getBaseContext(), clazz), requestCode);

    }
//
//    @Override
//    public void onClick(View v) {
//        super.onClick(v);
//        switch (v.getId()){
//            case R.id.back:
//                finish();
//                break;
//        }
//    }

    private String channel="";

    public void pay(){
        try {
            HashMap<String, String> map = new HashMap<>();
            AESCrypt aesCrypt = new AESCrypt();
            map.put("channel", channel);
            map.put("amount", price);
            map.put("ordernum", dingdan.oid);
            map.put("subject", "先锋的订单");
            map.put("body", "先锋打车消费");
            String json = JsonUtils.toJson(map);
            String d = StringUtil.replaceBlank(aesCrypt.encrypt(json));

            OkHttpUtils.post()
                    .url(Const.BASE_URL+"api.php/pay/pay")
//                    .addParams("args", Util.replaceBlank(aesCrypt.encrypt(json)))
                    .addParams("args", d)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call,Exception e, int i) {
                            Toast.makeText(getBaseContext(), "订单创建失败", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onResponse(String response, int i) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
//                                if (jsonObject.getString("code").equals("200")) {
                                    Pingpp.createPayment(ZhifuActivity.this, response);
//                                    Toast.makeText(getApplicationContext(), "订单已完成", Toast.LENGTH_SHORT).show();
//                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
//            Log.i("GGGG","denglu加密==="+ Util.replaceBlank(aesCrypt.encrypt(json))+"     lainjie==="+CarAppConts.base_url+"login_with_reg&args="+Util.replaceBlank(aesCrypt.encrypt(json)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


//    public void wx(){
//        try {
//            HashMap<String, String> map = new HashMap<>();
//            AESCrypt aesCrypt = new AESCrypt();
//            map.put("channel", channel);
//            map.put("amount", dingdan.price);
//            map.put("ordernum", dingdan.oid);
//            map.put("subject", "趣哒的订单");
//            map.put("body", "");
//            String json = JsonUtils.toJson(map);
//            String d = Util.replaceBlank(aesCrypt.encrypt(json));
//            OkHttpUtils.post()
//                    .url("http://139.196.5.108/pingxx/api/pay.php")
////                    .addParams("args", Util.replaceBlank(aesCrypt.encrypt(json)))
//                    .addParams("args", d)
//
//                    .build()
//                    .execute(new StringCallback() {
//                        @Override
//                        public void onError(Call call,Exception e, int i) {
//                            Toast.makeText(getBaseContext(), "订单创建失败", Toast.LENGTH_LONG).show();
//                        }
//
//                        @Override
//                        public void onResponse(String response, int i) {
//                            try {
//                                JSONObject jsonObject = new JSONObject(response);
////                                if (jsonObject.getString("code").equals("200")) {
//                                Pingpp.createPayment(ZhifuActivity.this, response);
////                                    Toast.makeText(getApplicationContext(), "订单已完成", Toast.LENGTH_SHORT).show();
////                                }
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    });
////            Log.i("GGGG","denglu加密==="+ Util.replaceBlank(aesCrypt.encrypt(json))+"     lainjie==="+CarAppConts.base_url+"login_with_reg&args="+Util.replaceBlank(aesCrypt.encrypt(json)));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //支付页面返回处理
        if (requestCode == Pingpp.REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getExtras().getString("pay_result");

                // 处理返回值
                // "success" - 支付成功
                // "fail"    - 支付失败
                // "cancel"  - 取消支付
                // "invalid" - 支付插件未安装（一般是微信客户端未安装的情况）
                switch (result){
                    case "success":
                        Toast.makeText(getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
//                        Stroke stroke = new Stroke();
//                        stroke.id = dingdan.id;
//                        Bundle bundle = new Bundle();
//                        bundle.putSerializable("stroke",stroke);
//                        startActivity(new Intent(this, IndexFormActivity.class).putExtra("data", bundle));
                        finish();
                        break;
                    case "fail":
                        Toast.makeText(getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
                        break;
                    case "cancel":
                        Toast.makeText(getApplicationContext(), "取消支付", Toast.LENGTH_SHORT).show();
                        break;
                    case "invalid":
                        Toast.makeText(getApplicationContext(), "支付插件未安装", Toast.LENGTH_SHORT).show();
                        break;
                }

                String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
                String extraMsg = data.getExtras().getString("extra_msg"); // 错误信息
                String test = "";
//                showMsg(result, errorMsg, extraMsg);
            }
        }

        if (requestCode == 1021 && resultCode == 2010) {
            cid = data.getStringExtra("cid");
//            youhuiquan.setText(data.getStringExtra("msg"));

        }
    }

    public void yuePay(){
        //获取用户钱包余额
        try {
            HashMap<String, String> map = new HashMap<>();
            AESCrypt aesCrypt = new AESCrypt();
            map.put("order_id", dingdan.id);
            map.put("coupon_id", cid);
            String json = JsonUtils.toJson(map);
            String d = StringUtil.replaceBlank(aesCrypt.encrypt(json));
            OkHttpUtils.post()
                    .url(Const.BASE_URL + "c=infoOrderCar&a=user_payOrder")
                    .addParams("args", d)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int i) {
                            Toast.makeText(getBaseContext(), "钱包余额获取失败", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onResponse(String response, int i) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (jsonObject.getString("code").equals("200")) {
                                    Toast.makeText(getApplicationContext(), "订单已完成", Toast.LENGTH_SHORT).show();
                                    finish();
                                }else{
                                    Toast.makeText(getApplicationContext(), "余额不足，支付失败", Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
//            Log.i("GGGG","denglu加密==="+ Util.replaceBlank(aesCrypt.encrypt(json))+"     lainjie==="+CarAppConts.base_url+"login_with_reg&args="+Util.replaceBlank(aesCrypt.encrypt(json)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void offPay(){
        try {
            HashMap<String, String> map = new HashMap<>();
            AESCrypt aesCrypt = new AESCrypt();
            map.put("amount", dingdan.price);
            map.put("ordernum", dingdan.oid);
            map.put("channel", "cash");
            String json = JsonUtils.toJson(map);
            String d = StringUtil.replaceBlank(aesCrypt.encrypt(json));
            OkHttpUtils.post()
                    .url(Const.BASE_URL + "api.php/order/cash")
                    .addParams("args", d)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call,Exception e, int i) {
                            Toast.makeText(getBaseContext(), "线下支付失败", Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onResponse(String response, int i) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                if (jsonObject.getString("code").equals("200")) {
                                    Toast.makeText(getApplicationContext(), "现金支付成功，等待司机确认", Toast.LENGTH_SHORT).show();
                                    finish();
                                }else{
                                    Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
//            Log.i("GGGG","denglu加密==="+ Util.replaceBlank(aesCrypt.encrypt(json))+"     lainjie==="+CarAppConts.base_url+"login_with_reg&args="+Util.replaceBlank(aesCrypt.encrypt(json)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected CharSequence provideTitle() {
        return "订单详情";
    }
}
